package com.weetop.aklyscan.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.google.zxing.activity.CaptureActivity;
import com.honeywell.aidc.AidcManager;
import com.honeywell.aidc.BarcodeFailureEvent;
import com.honeywell.aidc.BarcodeReadEvent;
import com.honeywell.aidc.BarcodeReader;
import com.honeywell.aidc.TriggerStateChangeEvent;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.qmuiteam.qmui.layout.QMUIButton;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.base.BaseActivity;
import com.weetop.aklyscan.base.mvp.BaseModel;
import com.weetop.aklyscan.bean.FittingDetailBean;
import com.weetop.aklyscan.bean.InStockItemBean;
import com.weetop.aklyscan.bean.IntoProductSaveBean;
import com.weetop.aklyscan.bean.OutStockItemBean;
import com.weetop.aklyscan.bean.ProductDetailBean;
import com.weetop.aklyscan.bean.ScanGoodsCodeBean;
import com.weetop.aklyscan.bean.TypeInfo;
import com.weetop.aklyscan.bean.ZXGoodsInfo;
import com.weetop.aklyscan.presenter.ScanOutPresent;
import com.weetop.aklyscan.utils.BaseUtils;
import com.weetop.aklyscan.view.ScanOutView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cc.shinichi.library.tool.utility.ui.ToastUtil;

import static com.weetop.aklyscan.utils.Constant.INTENT_EXTRA_KEY_QR_SCAN;

public class ScanOutActivity extends BaseActivity<ScanOutPresent> implements ScanOutView, CommonRecyclerAdapter.OnItemClickListener, BarcodeReader.BarcodeListener, BarcodeReader.TriggerListener {
    private static final int HUOJIA_CODE = 12000;
    private static final int REQUEST_HUOJIA_CODE_SCAN_ONE = 22000;

//    @BindView(R.id.iv_back)
//    ImageView ivBack;
    @BindView(R.id.rcy_data)
    RecyclerView rcyData;
    @BindView(R.id.rcy_data2)
    RecyclerView rcyData2;
    @BindView(R.id.rcy_data3)
    RecyclerView rcyData3;
    @BindView(R.id.order_type_spinner)
    TextView orderTypeSpinner;
    @BindView(R.id.tv_order_code)
    TextView tvOrderCode;
    @BindView(R.id.tv_chuku_zongliang)
    EditText tvChukuZongliang;
    @BindView(R.id.btn_chuku_save)
    QMUIButton btnChukuSave;
    @BindView(R.id.scan_out_rootview)
    RelativeLayout scanOutRootview;
    @BindView(R.id.tv_totle_postion)
    TextView tvTotlePostion;

    @BindView(R.id.chanpin_ll)
    LinearLayout chanpin_ll;
    @BindView(R.id.peijian_ll)
    LinearLayout peijian_ll;
    @BindView(R.id.peijian_ll1)
    LinearLayout peijian_ll1;
    @BindView(R.id.xinghao)
    TextView xinghao;
    @BindView(R.id.mingcheng)
    TextView mingcheng;
    private CommonRecyclerAdapter<OutStockItemBean.ShopData> adapter1;
    private CommonRecyclerAdapter<FittingDetailBean> adapter12;
    private CommonRecyclerAdapter<InStockItemBean> adapter2;
    private CommonRecyclerAdapter<InStockItemBean> adapter3;
    // 产品类型：1产品；2配件
    private int inStockType = 1;
    // 扫码类型：1产品序列号  2配件编号  3中转箱条码
    private int scanType = 1;
    private String orderCode;
    private List<OutStockItemBean.ShopData> productISList;
    private List<FittingDetailBean> fittingDetailBeanList;
    private List<InStockItemBean> list = new ArrayList<>();
    private String barcode;
    private HashMap<String, Integer> fittingMap;

    private String[] into10Item;
    private String[] into11Item;
    private String[] into11Code;

    int goodNum = 0;


    @Override
    protected ScanOutPresent createPresenter() {
        return new ScanOutPresent(this, mActivity);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_out);
        ButterKnife.bind(this);

        initView();
        initScan();
    }

    private void initView() {
        rcyData2.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter2 = new CommonRecyclerAdapter<InStockItemBean>(mActivity, R.layout.item_scanout2, list) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, InStockItemBean item, int position) {
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.tv_huopin_code, item.getGoods_code());
                helper.setText(R.id.tv_huopin_xinghao, item.getGoods_model());
                helper.setText(R.id.tv_huopin_mingcheng, item.getGoods_name());
                String type = item.getGoods_type() == 1 ? "产品" : "配件";
                helper.setText(R.id.tv_suoshu_huojia_zuobiao, item.getWarehouse_coordinates());
//                helper.setVisible(R.id.btn_delete, View.INVISIBLE);
                helper.setOnClickListener(R.id.btn_delete, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        adapter2.remove(item);
                        list.remove(item);
                        adapter2.notifyDataSetChanged();
                    }
                });
            }
        };
        rcyData2.setAdapter(adapter2);

        rcyData3.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter3 = new CommonRecyclerAdapter<InStockItemBean>(mActivity, R.layout.item_in_wx_peijian, list) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, InStockItemBean item, int position) {
                helper.setText(R.id.tv_xuhao, position + 1 + "");
//                helper.setText(R.id.tv_huopin_sn, item.getGoods_code());
//                helper.setText(R.id.tv_huopin_xinghao, item.getGoods_type() + "");
                helper.setText(R.id.tv_huopin_mingcheng, item.getGoods_name());
//                helper.setText(R.id.tv_xiangnei_huojia, item.getCount() + "");
                String type = item.getGoods_type() == 1 ? "产品" : "配件";
                helper.setText(R.id.tv_huopin_leixing, type);
                helper.setText(R.id.tv_xiangnei_shuliang, item.getCount() + "");
//                helper.setVisible(R.id.btn_delete, View.INVISIBLE);
                helper.setOnClickListener(R.id.btn_delete, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        adapter3.remove(item);
                        list.remove(item);
                        adapter3.notifyDataSetChanged();
                    }
                });
            }
        };
        rcyData3.setAdapter(adapter3);

        mPresenter.Into10();
        mPresenter.Into11();
//        orderSpinner.setTag("1");
    }

    @Override
    public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int position) {
        if (inStockType == 1) {
//            mPresenter.scanHuoPinCode("1", productISList.get(position).getCode());
//            mPresenter.scanHuoPinCode("1", "202007170004");
        } else {
//            mPresenter.scanHuoPinCode("1", fittingDetailBeanList.get(position).getCode());
//            mPresenter.scanHuoPinCode("1", "202007170004");
        }
    }

    @Override
    public void getOutStockDetail01Success(BaseModel<List<ProductDetailBean>> o,final int b) {
//        productISList = o.getData();
//        if (productISList != null && productISList.size() > 0) {
//            rcyData.setLayoutManager(new LinearLayoutManager(mActivity));
//            adapter1 = new CommonRecyclerAdapter<ProductDetailBean>(mActivity, R.layout.item_scanout1, productISList) {
//                @Override
//                public void onUpdate(BaseAdapterHelper helper, ProductDetailBean item, int position) {
//                    helper.setText(R.id.tv_xuhao, position + 1 + "");
//                    helper.setText(R.id.tv_huopin_xinghao, item.getGoods_model());
//                    helper.setText(R.id.tv_huopin_mingcheng, item.getGoods_name());
//                    helper.setText(R.id.tv_huopin_leixing, "产品");
//                    helper.setText(R.id.tv_yingru_zongliang, "");
//                    EditText weiru = helper.getView(R.id.et_weiruzongliang);
//                    View line = helper.getView(R.id.line);
//
//                    weiru.setVisibility(View.GONE);
//                    line.setVisibility(View.GONE);
//                    weiru.setEnabled(false);
//                }
//            };
//            adapter1.setOnItemClickListener(this);
//            rcyData.setAdapter(adapter1);
//        }
    }

    @Override
    public void getOutStockDetail02Success(BaseModel<List<FittingDetailBean>> o) {
//        fittingDetailBeanList = o.getData();
//        if (fittingDetailBeanList != null && fittingDetailBeanList.size() > 0) {
//            rcyData.setLayoutManager(new LinearLayoutManager(mActivity));
//            adapter12 = new CommonRecyclerAdapter<FittingDetailBean>(mActivity, R.layout.item_scanout1, fittingDetailBeanList) {
//                @Override
//                public void onUpdate(BaseAdapterHelper helper, FittingDetailBean item, int position) {
//                    helper.setText(R.id.tv_xuhao, position + 1 + "");
//                    helper.setText(R.id.tv_huopin_xinghao, item.getMatter_code());
//                    helper.setText(R.id.tv_huopin_mingcheng, item.getMatter_name());
//                    helper.setText(R.id.tv_huopin_leixing, "配件");
//                    helper.setText(R.id.tv_yingru_zongliang, item.getNumber() + "");
//                    EditText weiru = helper.getView(R.id.et_weiruzongliang);
//                }
//            };
//            rcyData.setAdapter(adapter12);
//        }
//        if (list.size() > 0) {
//            list.clear();
//            adapter2.clear();
//        }
    }

    @Override
    public void getGoodsListSuccess(BaseModel<List<ScanGoodsCodeBean>> o) {
//        List<ScanGoodsCodeBean> goodsCodeBeans = o.getData();
////        list.clear();
//        if (goodsCodeBeans != null && goodsCodeBeans.size() > 0) {
//            list.addAll(goodsCodeBeans);
//            adapter2.addAll(goodsCodeBeans);
//        } else {
//            ToastUtils.showShort("无结果");
//        }

    }

    @Override
    public void getInto10Success(BaseModel<List<TypeInfo>> o) {
        List<TypeInfo> data = o.getData();
        into10Item = new String[data.size()];
        for (int i = 0; i < data.size(); i++) {
            into10Item[i] = data.get(i).getName();
        }
    }

    @Override
    public void getInto11Success(BaseModel<List<TypeInfo>> o) {

        List<TypeInfo> data = o.getData();
        into11Item = new String[data.size()];
        into11Code = new String[data.size()];
        for (int i = 0; i < data.size(); i++) {
            into11Item[i] = data.get(i).getName();
            into11Code[i] = data.get(i).getId();
        }
    }

    @Override
    public void getOut01Success(BaseModel<OutStockItemBean> o) {
        productISList = o.getData().getShop_data();
        goodNum = o.getData().getAll_count();
        tvTotlePostion.setText(o.getData().getAll_count() + "");
        if (productISList != null && productISList.size() > 0) {
            rcyData.setLayoutManager(new LinearLayoutManager(mActivity));
            adapter1 = new CommonRecyclerAdapter<OutStockItemBean.ShopData>(mActivity, R.layout.item_scanout_out, productISList) {
                @Override
                public void onUpdate(BaseAdapterHelper helper, OutStockItemBean.ShopData item, int position) {
                    helper.setText(R.id.tv_xuhao, position + 1 + "");
                    helper.setText(R.id.tv_huopin_xinghao, item.getGoods_model());
                    helper.setText(R.id.tv_huopin_mingcheng, item.getGoods_name());
                    helper.setText(R.id.tv_huopin_dindan, item.getNum() + "");
                }
            };
            adapter1.setOnItemClickListener(this);
            rcyData.setAdapter(adapter1);
        } else {
            adapter1.clear();
            adapter1.notifyDataSetChanged();
        }
    }

    @Override
    public void getInto08Success(BaseModel<ZXGoodsInfo> o) {
        ZXGoodsInfo data = o.getData();
        InStockItemBean goodsItems = new InStockItemBean();
        goodsItems.setGoods_code(data.getSerial_code());
        goodsItems.setGoods_name(data.getGoods_name());
        goodsItems.setGoods_model(data.getGoods_model());
        goodsItems.setCount(1);
        //状态:-1已作废；0未入库；1在库里；2未出库；3已出库
        goodsItems.setStatus(data.getStatus());
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getGoods_code().equals(goodsItems.getGoods_code())) {
//                MyDialogUtil.showDialog(getActivity(), "无效");
//                playRing("shujuwuxiao.mp3");
                return;
            }
        }
        for (int i = 0; i < productISList.size(); i++) {
            if (goodsItems.getGoods_model().equals(productISList.get(i).getGoods_model())) {
                list.add(goodsItems);
                adapter2.add(goodsItems);
                rcyData2.smoothScrollToPosition(list.size());
//                playRing("shujuyouxiao.mp3");
                return;
            }
        }
//        MyDialogUtil.showDialog(getActivity(), "无效");
//        playRing("shujuwuxiao.mp3");
    }

    @Override
    public void getOut03Success(BaseModel<String> o) {
        ToastUtil.getInstance()._short(ScanOutActivity.this, "操作成功");
        list.clear();
        adapter1.clear();
        adapter1.notifyDataSetChanged();
        adapter2.clear();
        adapter2.notifyDataSetChanged();
        adapter3.clear();
        adapter3.notifyDataSetChanged();
        tvTotlePostion.setText("系统自动绑定");
//        playRing("chukuwancheng.mp3");
    }

    @Override
    public void showError(String msg) {
        super.showError(msg);
        ToastUtil.getInstance()._short(ScanOutActivity.this, msg);
    }

    @Override
    public void saveOutKuSuccess(BaseModel<Object> o) {
        ToastUtils.showShort("出库成功");
    }

    @OnClick({R.id.order_type_spinner, R.id.btn_chuku_save, R.id.tv_order_code, R.id.button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.order_type_spinner:
                if (into11Item == null) {
                    return;
                }
                XPopup.get(ScanOutActivity.this).asCenterList("请选择凭证类型", into11Item,
                        // null, /** 图标Id数组，可无 **/
                        // 1,    /** 选中的position，默认没有选中效果 **/
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                if (adapter1 != null) {
                                    adapter1.clear();
                                    adapter1.notifyDataSetChanged();
                                }
                                orderTypeSpinner.setText(text);
                                orderTypeSpinner.setTag(into11Code[position]);
                                tvTotlePostion.setText("系统自动绑定");
                            }
                        })
                        .show();
                break;
//            case R.id.iv_back:
//                AlertDialog.Builder normalDialog = new AlertDialog.Builder(ScanOutActivity.this);
//                normalDialog.setTitle("提示");
//                normalDialog.setMessage("返回主页，当前数据将清除，是否返回");
//                normalDialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        finish();
//                    }
//                });
//                normalDialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                });
//                normalDialog.create().show();
//                break;
            case R.id.btn_chuku_save:
                if (list.size() != goodNum) {
                    ToastUtil.getInstance()._short(ScanOutActivity.this, "出库数量不正确");
                    return;
                }
                try {
                    if (BaseUtils.fastClick()) {
//                        if (((String) orderSpinner.getTag()).equals("1")) {//产品
                            List<IntoProductSaveBean> items = new ArrayList<>();
                            JSONArray jsonArray = new JSONArray();
                            JSONObject tmpObj = null;
                            for (int i = 0; i < list.size(); i++) {
                                tmpObj = new JSONObject();
                                tmpObj.put("code", list.get(i).getGoods_code());
                                tmpObj.put("goods_model", list.get(i).getGoods_model());
                                jsonArray.put(tmpObj);
                                tmpObj = null;
                            }
                            if (jsonArray.length() > 0) {
                                String itemsString = GsonUtils.toJson(items);
                                mPresenter.Out03("", tvOrderCode.getText().toString().trim(), jsonArray);
                            } else {
                                ToastUtils.showShort("无新增产品");
                            }
//                        } else {// 配件
//
//                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.button:
                if (TextUtils.isEmpty(orderTypeSpinner.getText().toString())) {
                    ToastUtil.getInstance()._short(ScanOutActivity.this, "出库凭证类型不能为空");
                    return;
                }
                mPresenter.Out01("", (String) orderTypeSpinner.getTag(), tvOrderCode.getText().toString().trim());
                break;
        }
    }


    private void startScanQrCode() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            requestPermissions(new String[]{Manifest.permission.CAMERA}, HUOJIA_CODE);
            return;
        }
        // 二维码扫描
        Intent intent = new Intent(ScanOutActivity.this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_HUOJIA_CODE_SCAN_ONE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || grantResults == null) {
            return;
        }
        switch (requestCode) {
            case HUOJIA_CODE:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startScanQrCode();
                } else {        // 授权被禁止
                    ToastUtils.showShort("请至权限中心打开本应用的相机访问权限");
                }
                break;
            default:
        }
    }

    /**
     * 扫码结果回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描结果回调
        if (requestCode == REQUEST_HUOJIA_CODE_SCAN_ONE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(INTENT_EXTRA_KEY_QR_SCAN);
            // scanResult 就是扫描二维码得到的字符串，再次可以根据自己的逻辑编写代码
            ToastUtils.showShort("扫码结果：" + scanResult);
            if (!TextUtils.isEmpty(scanResult)) {
                if (scanType == 0) {
                    tvOrderCode.setText(scanResult);
                    orderCode = scanResult;
                    if (inStockType == 1) {
                        mPresenter.outStockDetail01(inStockType + "", scanResult,1);
                    } else {
                        mPresenter.outStockDetail02(inStockType + "", scanResult);
                    }
                } else {
                    mPresenter.scanHuoPinCode(scanType + "", scanResult);
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            AlertDialog.Builder normalDialog = new AlertDialog.Builder(ScanOutActivity.this);
            normalDialog.setTitle("提示");
            normalDialog.setMessage("返回主页，当前数据将清除，是否返回");
            normalDialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            });
            normalDialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            normalDialog.create().show();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mPresenter.Into08("1", (String) msg.obj,"");
                    break;
            }
        }
    };

    AidcManager manager;
    BarcodeReader barcodeReader;

    private void initScan() {
        //第一步：获取扫描资源，设置扫描参数，开启扫描功能
        AidcManager.create(ScanOutActivity.this, new AidcManager.CreatedCallback() {
            @Override
            public void onCreated(AidcManager aidcManager) {
                manager = aidcManager;
                barcodeReader = manager.createBarcodeReader();
                try {
                    barcodeReader.claim(); //开启扫描功能
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //第二步：添加侧面扫描键事件监听和条码事件监听
                barcodeReader.addTriggerListener(ScanOutActivity.this);
                barcodeReader.addBarcodeListener(ScanOutActivity.this);
            }
        });
    }

    @Override
    public void onBarcodeEvent(BarcodeReadEvent barcodeReadEvent) {
        String barcodeData = barcodeReadEvent.getBarcodeData();
        Message message = new Message();
        message.what = 1;
        message.obj = barcodeData;
        handler.sendMessage(message);
    }

    @Override
    public void onFailureEvent(BarcodeFailureEvent barcodeFailureEvent) {
        System.out.println("失败：");
    }

    @Override
    public void onTriggerEvent(TriggerStateChangeEvent triggerStateChangeEvent) {
        System.out.println("按键：");
        if (triggerStateChangeEvent.getState() == true) {
            try {
                barcodeReader.light(true);        //开启补光
                barcodeReader.aim(true);        //开启瞄准线
                barcodeReader.decode(true);        //开启解码
            } catch (Exception e) {
                Toast.makeText(ScanOutActivity.this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        } else if (triggerStateChangeEvent.getState() == false) {
            try {
                barcodeReader.light(false);        //关闭补光
                barcodeReader.aim(false);        //关闭瞄准线
                barcodeReader.decode(false);    //关闭解码
            } catch (Exception e) {
                Toast.makeText(ScanOutActivity.this, "关闭扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (barcodeReader != null) {
            try {
                barcodeReader.claim();        //开启扫描功能
            } catch (Exception e) {
//                Toast.makeText(this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (barcodeReader != null) {
            barcodeReader.release();        //释放扫描资源
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (barcodeReader != null) {
            barcodeReader.removeBarcodeListener(this);
            barcodeReader.removeTriggerListener(this);
            barcodeReader.close();
        }
        if (manager != null) {
            manager.close();
        }
    }
}
